import 'package:flutter/material.dart';
import 'package:word_range_client/pojo/vo/WordMappingVo.dart';
import 'package:word_range_client/viewModels/WordBookViewModel.dart';
import 'package:word_range_client/widgets/general/PartingLine.dart';

import '../../pojo/dto/PageDto.dart';
import '../../pojo/queery/WordQuery.dart';
import '../general/Toastification.dart';

class Wordlist extends StatefulWidget {
  const Wordlist({super.key, required this.bookId, required this.wordCount});
  final String bookId;
  final int wordCount;


  @override
  State<Wordlist> createState() => _WordlistState();
}

class _WordlistState extends State<Wordlist> with TickerProviderStateMixin {
  bool _isLoading = true;
  List<Widget> _items = [];
  int _pageNo = 1;
  int _pageSize = 10;
  int _totalPages = 0;
  Key _listKey = UniqueKey();

  // 用于存储每个列表项的动画控制器
  List<AnimationController> _animationControllers = [];

  @override
  void initState() {
    super.initState();
    _updateTotalPages();
    _loadData();
  }

  @override
  void dispose() {
    // 释放所有动画控制器
    for (var controller in _animationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  void _updateTotalPages() {
    setState(() {
      _totalPages = widget.wordCount ~/ _pageSize;
      if (widget.wordCount % _pageSize != 0) {
        _totalPages++;
      }
    });
  }

  Widget _buildItem(WordMappingVo wordMappingVo, int index) {
    return FadeTransition(
      opacity: Tween<double>(begin: 0.0, end: 1.0).animate(
        CurvedAnimation(
          parent: _animationControllers[index],
          curve: Curves.easeIn,
        ),
      ),
      child: Card(
        color: Theme.of(context).colorScheme.secondary.withAlpha(240),
        elevation: 2,
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "${wordMappingVo.word} - ${wordMappingVo.tran}",
                style: const TextStyle(fontSize: 17),
              ),
              const PartingLine(),
              Text(
                "${wordMappingVo.example}",
                style: const TextStyle(fontSize: 13),
              ),
              Text(
                "${wordMappingVo.exampleTran}",
                style: const TextStyle(fontSize: 13),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _nextPage() async {
    if (_pageNo >= _totalPages) {
      return;
    }
    setState(() {
      _pageNo++;
    });
    _loadData();
  }

  void _previousPage() async {
    if (_pageNo <= 1) {
      return;
    }
    setState(() {
      _pageNo--;
    });
    _loadData();
  }

  Widget _buildBottomButton() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _PreviousPageButton(onPressed: _previousPage),
        _PageNumber(pageNo: _pageNo, totalPages: _totalPages),
        _NextPageButton(onPressed: _nextPage),
      ],
    );
  }

  void _loadData() async {
    WordBookViewModel wordBookViewModel = WordBookViewModel();
    Toastification toastification = Toastification(context: context);
    WordQuery wordQuery = WordQuery(
      bookId: widget.bookId,
      pageNo: _pageNo,
      pageSize: _pageSize,
      sort: "word",
      isAsc: true,
    );
    PageDto result = await wordBookViewModel.getWordListOnBookId(wordQuery);

    // 清空旧数据和动画控制器
    _items.clear();
    for (var controller in _animationControllers) {
      controller.dispose();
    }
    _animationControllers.clear();

    // 处理新数据
    if (result.list != null && result.list!.isNotEmpty) {
      for (var i = 0; i < result.list!.length; i++) {
        // 为每个列表项创建动画控制器
        final controller = AnimationController(
          vsync: this,
          duration: const Duration(milliseconds: 120),
        );
        _animationControllers.add(controller);

        WordMappingVo wordMappingVo = WordMappingVo(
          id: result.list![i]["id"],
          bookId: result.list![i]["bookId"],
          word: result.list![i]["word"],
          tran: result.list![i]["tran"],
          example: result.list![i]["example"] ?? "暂无例句",
          exampleTran: result.list![i]["exampleTran"] ?? "",
          createTime: result.list![i]["createTime"] ?? "",
          updateTime: result.list![i]["updateTime"] ?? "",
        );
        _items.add(_buildItem(wordMappingVo, i));
      }

      // 启动所有动画
      for (var controller in _animationControllers) {
        controller.forward();
      }
    } else {
      // 弹出通知
      toastification.showWarning("哦吼！这好像是本空词书");
    }

    // 更新 UI
    setState(() {
      _isLoading = false;
      _listKey = UniqueKey(); // 改变 Key，强制刷新 ListView
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const _Loading();
    }
    return Column(
      children: [
        Expanded(
          child: _items.isEmpty
              ? Center(
                  child: Text(
                    "词书为空",
                    style: TextStyle(
                      fontSize: 20,
                      color: Colors.grey[600],
                    ),
                  ),
                )
              : ListView(
                  key: _listKey,
                  children: _items,
                ),
        ),
        _buildBottomButton(),
      ],
    );
  }
}



class _Loading extends StatelessWidget {
  const _Loading({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          LinearProgressIndicator(),
          Text("Loading...")
        ],
      ),
    );
  }
}

// 上一页按钮
class _PreviousPageButton extends StatelessWidget {
  const _PreviousPageButton({
    super.key,
    required this.onPressed,
  });

  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: onPressed,
      icon: const Icon(Icons.arrow_back),
    );
  }
}

//下一页按钮
class _NextPageButton extends StatelessWidget {
  const _NextPageButton({
    super.key,
    required this.onPressed,
  });

  final VoidCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: onPressed,
      icon: const Icon(Icons.arrow_forward),
    );
  }
}

// 页码显示
class _PageNumber extends StatelessWidget {
  const _PageNumber({
    super.key,
    required this.pageNo,
    required this.totalPages,
  });

  final int pageNo;
  final int totalPages;

  @override
  Widget build(BuildContext context) {
    return Text(
      "第 $pageNo / $totalPages 页",
      style: const TextStyle(
        fontSize: 16,
      ),
    );
  }
}

